package com.sam.im.heiqun.uis.activities;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PopupMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;

import com.sam.im.heiqun.R;
import com.sam.im.heiqun.constant.Constant;
import com.sam.im.heiqun.entities.ColactionEntity;
import com.sam.im.heiqun.entities.ImMessage;
import com.sam.im.heiqun.entities.MsgEntity;
import com.sam.im.heiqun.entities.ValidateEntivity;
import com.sam.im.heiqun.entities.VedioEntity;
import com.sam.im.heiqun.entities.VoiceEntity;
import com.sam.im.heiqun.entities.beans.ImageInfoBean;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.uis.adapters.ChatRecyclerAdapter;
import com.sam.im.heiqun.uis.adapters.ColactionAdapter;
import com.sam.im.heiqun.utils.IMMessageUtil;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.sam.im.heiqun.view.PullToRefreshListener;
import com.sam.im.heiqun.view.PullToRefreshRecyclerView;
import com.google.gson.Gson;
import com.yuyh.library.nets.callbacks.AbsAPICallback;
import com.yuyh.library.nets.exceptions.ApiException;
import com.yuyh.library.uis.activitys.BaseSwipeBackActivity;
import com.yuyh.library.utils.DividerItemDecorationUtils;
import com.yuyh.library.utils.ScreenUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 收藏页面
 */
public class CollectionActivity extends BaseSwipeBackActivity {
    @BindView(R.id.pre_v_back)
    ImageView preVBack;
    @BindView(R.id.recycler_view)
    PullToRefreshRecyclerView recyclerView;
    ColactionAdapter adapter ;
    List<ColactionEntity.ListBean> datas = new ArrayList<>();
    int pageNo = 1;
    private PopupMenu popupMenu ;
    private Menu menu;
    private PGService mPgservice;
    private int tag;
    private long destid;

    @Override
    public int getContentViewId() {
        return R.layout.activity_collection;
    }
    @Override
    protected String getTitleText() {
        return getResources().getString(R.string.my_collect);
    }
    @Override
    protected void initViews(Bundle savedInstanceState) {
        adapter = new ColactionAdapter(this,datas);
        recyclerView.setAdapter(adapter);
        tag = getIntent().getIntExtra("tag",0);
        destid = getIntent().getLongExtra("destid", 0);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addItemDecoration(new DividerItemDecorationUtils(this, LinearLayoutManager.HORIZONTAL, ScreenUtil.dp2px(5), getResources().getColor(R.color.background)));
        getDatas();
        recyclerView.setPullRefreshEnabled(false);
        recyclerView.setPullToRefreshListener(new PullToRefreshListener() {
            @Override
            public void onRefresh() {

            }

            @Override
            public void onLoadMore() {
                pageNo++;
                getDatas();
            }
        });
        adapter.setOnlongClickListenler(new ColactionAdapter.OnlongClickListenler() {
            @Override
            public void longClick(View view,int position) {
                initMenu(view,datas.get(position).getId(),position);
            }
        });
        adapter.setOnCollecClickListenler(new ColactionAdapter.OnCollecClickListenler() {
            @Override
            public void onClick(View view, final int position) {

                ColactionEntity.ListBean listBean = datas.get(position);
                if (null==listBean){
                    showToast("数据出错，请刷新页面！");
                    return;
                }
                switch (getItemType(listBean)) {
                    case 2://图片
                        try {
                            ImagePagerActivity.ImageSize imageSize = new ImagePagerActivity.ImageSize(view.getMeasuredWidth(), view.getMeasuredHeight());
                            List<ImageInfoBean> photoUrls = new ArrayList<>();
                            photoUrls.add(new ImageInfoBean(IMMessageUtil.getImageUrl(listBean.getContent()),true));
                            ImagePagerActivity.startImagePagerActivity((CollectionActivity.this), photoUrls, 0, imageSize);
                        }catch (Exception e){
                            e.printStackTrace();
                        }

                        break;
                    case 1://文字
                    case 3://语音
                        ColactionDetailActivity.start(CollectionActivity.this, listBean);
                        break;
                    case 4://视频
                        try {
                            String contents = listBean.getContent();
                            VedioEntity vedioEntity = new Gson().fromJson(contents, VedioEntity.class);
                            String filepath = vedioEntity.getVedioUrl();
                            startActivity(Play2Activity.newIntent(CollectionActivity.this,filepath,vedioEntity,null));
                        }catch (Exception e){
                            e.printStackTrace();
                        }

                        break;
                    case 5:
//                                holder = new ColatVideoViewHolder(view, 5);
                        break;
                    case 6:
//                                holder = new ColatVideoViewHolder(view, 6);
                        break;
                }

//                AlertDialog.Builder builder = new AlertDialog.Builder(CollectionActivity.this);
//                builder.setTitle(getResources().getString(R.string.tip));
//                builder.setMessage(getResources().getString(R.string.is_send_message));
//                builder.setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                    }
//                });
//                builder.setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        ImMessage colactiontomsg = colactiontomsg(datas.get(position));
//                        Intent dataintent = new Intent();
//                        if (tag != 0) {//从聊天界面过来的
//                            dataintent.putExtra("imessage",colactiontomsg);
//                            setResult(112211,dataintent);
//                            finish();
//                        }else {
//                            Bundle bundle = new Bundle();
//                            bundle.putSerializable("msg",colactiontomsg);
//                            bundle.putInt("tag",11);
//                            startActivity(SelecteLocalFriendActivity.class,bundle);
//                        }
//                    }
//                });
//                AlertDialog dialog = builder.create();
//                dialog.show();
            }
        });
    }

    public int getItemType(ColactionEntity.ListBean listBean) {
        if (null != listBean) {
            try {
                return Integer.parseInt(listBean.getCategory());
            }catch (Exception e){e.printStackTrace();}

        }
        return 0;
    }

    private void getDatas() {
       // showProgress("正在加载");
        mPgservice = PGService.getInstance();
        mPgservice.getcolaction(pageNo+"", ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<ColactionEntity>() {
            @Override
            protected void onResultError(ApiException ex) {
               // hideProgress();
                ToolsUtils.showToast(CollectionActivity.this, getResources().getString(R.string.get_collect_fail));
                recyclerView.setLoadMoreComplete();
            }

            @Override
            public void onNext(ColactionEntity colactionEntity) {
                if (pageNo==1)datas.clear();
                if (colactionEntity != null) {
                    List<ColactionEntity.ListBean> list = colactionEntity.getList();
                    if (list.size()>0){
                        datas.addAll(list);
                        adapter.notifyDataSetChanged();
                        if (list.size()%20!=0){
                            recyclerView.setLoadingMoreEnabled(false);
                        }else {
                            recyclerView.setLoadingMoreEnabled(true);
                        }
                    }else {
                        adapter.notifyDataSetChanged();
                        recyclerView.setLoadingMoreEnabled(false);
                    }
                    recyclerView.setLoadMoreComplete();
                }
               // hideProgress();
        }
        });
    }

    @OnClick(R.id.pre_v_back)
    public void onViewClicked() {
        finish();
    }
    /**
     * @param view
     * @param
     */
    public void initMenu(View view, final String fravovitid , final int position) {
        popupMenu = new PopupMenu(this, view);
        menu = popupMenu.getMenu();
        // 通过XML文件添加菜单项
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.popup_menu_collect, menu);
        popupMenu.show();
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()){
                    case R.id.sendto://转发
                        ImMessage colactiontomsg = colactiontomsg(datas.get(position));
                        Intent dataintent = new Intent();
                        if (tag != 0) {//从聊天界面过来的
                            dataintent.putExtra("imessage",colactiontomsg);
                            setResult(112211,dataintent);
                            finish();
                        }else {
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("msg",colactiontomsg);
                            bundle.putInt("tag",11);
                            startActivity(SelecteLocalFriendActivity.class,bundle);
                        }
                        break;
                    case R.id.delete://删除
                        dodelete(fravovitid);
                        break;
                }
                return false;
            }
        });
    }

    private void dodelete(String fravovitid) {
        showProgress(getResources().getString(R.string.now_delete));
        mPgservice.deletelaction(fravovitid,ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<ValidateEntivity>() {
            @Override
            protected void onResultError(ApiException ex) {
                hideProgress();
                ToolsUtils.showToast(CollectionActivity.this,"删除失败");
            }

            @Override
            public void onNext(ValidateEntivity validateEntivity) {
                hideProgress();
                if (validateEntivity != null) {
                    ToolsUtils.showToast(CollectionActivity.this,validateEntivity.getInfo());
                    datas.clear();
                    pageNo=1;
                    getDatas();
                }
            }
        });
    }
    private ImMessage colactiontomsg(ColactionEntity.ListBean data){
        int messagetype = -1 ;
        int type = -1 ;
        int fromtype = tag ;
        float voiceTime = 0;
        String typetag = "",fileUrl = "";
        if (tag==1){
            typetag="_";
        }else if (tag==2){
            typetag="__";
        }
        String fromid = ToolsUtils.getMyUserId();
        fileUrl = data.getContent();
        switch (data.getCategory()){
            case "1"://文字
                try {
                    MsgEntity msgEntity = new Gson().fromJson(data.getContent(),MsgEntity.class);
                    if (msgEntity.getMsgCodes()!=null&&!"".equals(msgEntity.getMsgCodes())){//大表情
                       type = ChatRecyclerAdapter.TO_USER_EMOJI ;
                    }else {//小表情
                        type = ChatRecyclerAdapter.TO_USER_EMOJI_TEXT ;
                    }
                    messagetype = Constant.MESSAGE_TYPR_BQEMOJI;
                }catch (Exception e){//老文本
                    messagetype = Constant.MESSAGE_TYPR_TEXT;
                    type = ChatRecyclerAdapter.TO_USER_MSG ;
                }
                break;
            case "2"://图片
                messagetype = Constant.MESSAGE_TYPR_IMAGE;
                type = ChatRecyclerAdapter.TO_USER_IMG;
                break;
            case "3"://语音
                VoiceEntity msgEntity = new Gson().fromJson(data.getContent(),VoiceEntity.class);
                if (msgEntity!=null) {
                    voiceTime = Float.parseFloat(msgEntity.getTime());
                    fileUrl = msgEntity.getUrl();
                }

                messagetype = Constant.MESSAGE_TYPR_VOICE;
                type = ChatRecyclerAdapter.TO_USER_VOICE;
                break;
            case "4"://视频
                messagetype = Constant.MESSAGE_TYPR_VEDIO;
                type = ChatRecyclerAdapter.TO_USER_VEDIO;

                break;
            /*case 5:
                break;
            case 6:
                break;*/
        }
        ImMessage imMessage = ToolsUtils.getTbub(Constant.VERSION_MESSAGE_CHART, Constant.DEV_TYPE, 0, type, tag+"-" + destid + "-" + fromid + "-" + System.currentTimeMillis(),
                Long.parseLong(fromid), fromtype, destid,data.getContent(), messagetype,
                System.currentTimeMillis(), System.currentTimeMillis(), 0,fileUrl , fromid + typetag + destid, voiceTime,ToolsUtils.getUser().getHeadUrl());
        return imMessage;
    }


}
